package com.lin.filegraph.utils.parser.astutil;

import com.lin.filegraph.utils.moduledg.ModuleInfo;
import com.lin.filegraph.utils.moduledg.PomNode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: linhuaixu
 * @time: 2023/5/18 15:26
 */

public class ParsePom {
    public static List<ModuleInfo> getModule(String projectPath) {
        File folder = new File(projectPath);

        // 如果文件夹不存在
        if (!folder.exists()) {
            System.out.println("目录不存在：" + folder.getAbsolutePath());
            System.out.println("项目目录不存在");
        }
        else if(folder.isFile()){
            System.out.println("路径错误，是个文件而不是目录");
        }

        List<PomNode> poms = searchPom(folder);
        HashMap<String, PomNode> nodes = new HashMap<>();
        poms.forEach(o->{
            PomNode node = nodes.get(o.getParent());
            if(node!=null) {
                node.addChild(o);
            }
            nodes.put(o.getName(),o);
        });
        List<ModuleInfo> list = new ArrayList<>();
        List<PomNode> modules = poms.stream().filter(PomNode::hasNotChildren).collect(Collectors.toList());
        modules.forEach(o->{
            ModuleInfo moduleInfo = new ModuleInfo();
            moduleInfo.setModuleName(o.getName());
            moduleInfo.setModulePath(o.getPath());
//            System.out.println(o.getName()+"\t"+o.getPath());
            list.add(moduleInfo);
        });
        return list;
    }

    public static List<PomNode> searchPom(File folder){
        LinkedList<PomNode> poms = new LinkedList<>();
        File[] files = folder.listFiles();
        List<File> children = new ArrayList<>();
        for(File file : files){
            if(file.isDirectory()){
                children.add(file);
            }
            else {
                if("pom.xml".equals(file.getName())){
                    poms.addLast(new PomNode(file));
                }
            }
        }
        for (File child : children){
            poms.addAll(searchPom(child));
        }
        return poms;
    }
}

